<template>
  <el-card>
    <div class="mb-20px"
      ><h4 class="text-blue-400">{{ id != '-1' ? '编辑' : '新增' }}</h4></div
    >
    <el-row>
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
        >
          <el-form-item label="会员ID" prop="id">
            <el-input v-model="formData.id" placeholder="创建后自动生成" disabled />
          </el-form-item>
          <el-form-item label="会员名称" prop="membershipName">
            <el-input v-model="formData.membershipName" placeholder="请输入会员名称" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input v-model="formData.price" type="number" min="0" placeholder="请输入价格">
              <template #suffix>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="划线价" prop="underlinedPrice">
            <el-input
              v-model="formData.underlinedPrice"
              placeholder="请输入划线价格"
              type="number"
              min="0"
            >
              <template #suffix>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="咨询次数" prop="consultationFrequency">
            <el-input
              v-model="formData.consultationFrequency"
              placeholder="请输入咨询次数"
              type="number"
              min="0"
            >
              <template #suffix>次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="报名次数" prop="consultationFrequency">
            <el-input
              disabled
              v-model="formData.consultationFrequency"
              placeholder="同咨询次数"
              type="number"
              min="0"
            >
              <template #suffix>次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="有效期" prop="lifeSpan">
            <el-input v-model="formData.lifeSpan" placeholder="请输入有效期" type="number" min="0">
              <template #suffix>天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="会员说明" prop="membershipDescription">
            <Editor v-model="formData.membershipDescription" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-input
              :modelValue="formData.createTime && formatDate(formData.createTime)"
              placeholder="创建后自动生成"
              disabled
            />
          </el-form-item>
        </el-form>
        <div>
          <el-button
            @click="
              () => {
                $router.back()
                delVisitedView(route)
              }
            "
            >取 消</el-button
          >
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 认</el-button>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { MembershipSettingsApi, MembershipSettings } from '@/api/biz/membershipsettings'
import { formatDate } from '@/utils/formatTime'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { delVisitedView } = useTagsViewStore()
const route = useRoute()
const router = useRouter()

/** 会员设置 表单 */
defineOptions({ name: 'MembershipSettingsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const id = useRoute().params.id

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: id == '-1' ? undefined : Number(id),
  membershipName: undefined,
  price: undefined,
  underlinedPrice: undefined,
  consultationFrequency: undefined,
  registrationsFrequency: undefined,
  lifeSpan: undefined,
  membershipDescription: undefined,
  createTime: undefined
})
const formRules = reactive({
  membershipName: [{ required: true, message: '会员名称不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
  underlinedPrice: [{ required: true, message: '划线价不能为空', trigger: 'blur' }],
  consultationFrequency: [{ required: true, message: '咨询次数不能为空', trigger: 'blur' }],
  lifeSpan: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MembershipSettingsApi.getMembershipSettings(id)
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MembershipSettings
    data.registrationsFrequency = data.consultationFrequency
    if (formType.value === 'create') {
      await MembershipSettingsApi.createMembershipSettings(data)
      message.success(t('common.createSuccess'))
    } else {
      await MembershipSettingsApi.updateMembershipSettings(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    membershipName: undefined,
    price: undefined,
    underlinedPrice: undefined,
    consultationFrequency: undefined,
    registrationsFrequency: undefined,
    lifeSpan: undefined,
    membershipDescription: undefined,
    createTime: undefined
  }
  formRef.value?.resetFields()
}

open(id == '-1' ? 'create' : 'update', formData.value.id)
</script>
